<template>
    <div id="user-task-update-box">
        <el-container>
            <el-header>
                <div class="header-content">
                    <div class="left-content">
                        <div class="div-icon"></div>
                        <samp>基本信息</samp>
                    </div>
                    <div class="buttons-right">
                        <el-button type="primary" @click="submitForm(FormRef)"
                            id="user-task-update-submit">提交</el-button>
                        <el-button plain @click="closeForm" id="user-task-update-close">关闭</el-button>
                    </div>
                </div>

            </el-header>
            <el-main>
                <div class="form-container">
                    <el-form ref="FormRef" class="form-frame" :model="taskFrom" :rules="rules" label-width="auto"
                        :size="formSize">
                        <el-form-item label="任务名称：" prop="title" id="user-task-update-input-title">
                            <el-input v-model="taskFrom.title" placeholder="输入内容" id="user-task-update-input-title"
                                disabled />
                        </el-form-item>
                        <el-form-item label="任务内容：" prop="content" id="user-task-update-input-content">
                            <el-input v-model="taskFrom.content" type="textarea" placeholder="输入内容"
                                id="user-task-update-input-content" />
                        </el-form-item>
                        <el-form-item label="任务状态" id="admin-task-update-radio-workStatusId">
                            <el-radio-group v-model="taskFrom.workStatusId" id="admin-task-update-radio-workStatusId">
                                <el-radio :value="1">已完成</el-radio>
                                <el-radio :value="0">进行中</el-radio>
                                <el-radio :value="2">已到期</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="任务要求：" id="user-task-update-input-require">
                            <el-input type="textarea" placeholder="输入内容" v-model="taskFrom.require"
                                id="user-task-update-input-require" />
                        </el-form-item>
                        <el-form-item label="截止时间：" id="user-task-update-radio-endTime">
                            <el-date-picker v-model="taskFrom.endTime" type="date" placeholder="选择日期" clearable
                                format="YYYY-MM-DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss"
                                :disabledDate="beforeToday" id="user-task-update-radio-endTime" />
                        </el-form-item>
                        <!-- actio上传服务器的地址 -->
                        <el-form-item label="附件：" id="user-task-update-radio-file">
                            <!-- <input type="file" accept=".doc,.docx" style="margin-bottom: 10px;"  id="admin-task-update-radio-file"/> -->
                            <el-upload ref="upload" class="upload-demo" :before-upload="upload"
                                :before-remove="removeFile" :limit="1" id="user-task-update-radio-file">
                                <template #trigger>
                                    <el-button type="primary" plain id="user-task-update-radio-file">
                                        <el-icon style="font-size: 25px;margin-right: 15px;">
                                            <UploadFilled />
                                        </el-icon>上传
                                    </el-button>
                                </template>
                            </el-upload>


                            <div v-if="taskFrom.file" class="file-display">
                                <el-icon>
                                    <Document />
                                </el-icon>
                                <span class="file-name">{{ taskFrom.file.name }}</span>
                                <el-icon class="delete-icon" @click="removeFile">
                                    <Delete />
                                </el-icon>
                            </div>
                            <div>
                                <samp style="font-size: 15px; color:#888;">支持doc/docx格式附件,附件大小不能超过4M</samp>
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
            </el-main>
        </el-container>
    </div>
</template>


<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import { UploadFilled, Document, Delete } from '@element-plus/icons-vue'
import { getTaskById, userUpdateTask } from '@/api/index.js';
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute();

const tasks = JSON.parse(route.query.tasks) || ""

console.log(tasks);

const taskFrom = ref({
    id: '',
    title: '',
    content: '',
    require: '',
    endTime: '',
    updateTime: '',
    attachmentId: '',
    file: null,
    workStatusId: ''
})
const ee = ref('')


onMounted(() => {
    taskFrom.value = {
        id: tasks.id || '',
        title: tasks.title || '',
        content: tasks.content || '',
        userId: tasks.userId || '',
        workStatusId: Number(tasks.workStatusId || 0),
        endTime: dayjs(tasks.endTime * 1).format("YYYY-MM-DD hh:mm:ss") || '',
        updateTime: tasks.updateTime || '',
        require: tasks.require || '',
        attachmentId: tasks.attachmentId || '',
        file: tasks.file || null
    }

    ee.value = tasks.endTime
    console.log('表单数据:', taskFrom.value)
})

// taskFrom.value = {
//     ...tasks
// }

const FormRef = ref()

const today = new Date();
const formattedDate = today.toISOString().split('T')[0];

function beforeToday(time) {
    const todayStartOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
    return time.getTime() < todayStartOfDay;
}

const rules = reactive({
    title: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入任务内容', trigger: 'blur' },
    ]
})

// 处理文件选择
const handleFileChange = (event) => {
    const file = event.target.files[0]
    if (!file) return

    console.log('选择的文件:', file)

    // 检查文件类型
    const isDoc = file.type === 'application/msword' ||
        file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    if (!isDoc) {
        ElMessage.error('只能上传 DOC/DOCX 格式的文件!')
        event.target.value = '' // 清空选择
        return
    }

    // 检查文件大小（4MB = 4 * 1024 * 1024 bytes）
    const isLt4M = file.size / 1024 / 1024 < 4
    if (!isLt4M) {
        ElMessage.error('文件大小不能超过 4MB!')
        event.target.value = '' // 清空选择
        return
    }

    // 读取文件内容
    const reader = new FileReader()

    reader.onload = (e) => {
        try {
            // 获取文件的二进制数据
            const binaryData = new Uint8Array(e.target.result)
            console.log('文件二进制数据:', binaryData)

            // 存储二进制数据到 file
            taskFrom.value.file = binaryData
            // 存储文件名到 attachmentId
            // taskFrom.value.attachmentId = file.name

            ElMessage.success('文件已选择')
        } catch (error) {
            console.error('文件处理错误:', error)
            ElMessage.error('文件处理失败')
        }
    }

    reader.onerror = (error) => {
        console.error('文件读取错误:', error)
        ElMessage.error('文件读取失败')
    }

    // 以二进制格式读取文件
    reader.readAsArrayBuffer(file)
}

const upload = (file) => {
    console.log(file);

    taskFrom.value.file = file;
}
const upload2 = (file) => {
    console.log(file);

    taskFrom.value.file = file;
}


// 获取任务详情
const getTask = () => {
    let id = ''
    getTaskById({ appointor_id: id }).then((res) => {
        console.log(res);

    }).catch((err) => {

    });
}

// 提交表单
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (taskFrom.value.attachmentId == null || taskFrom.value.attachmentId == '') {
                delete taskFrom.value.attachmentId
            }
            if (taskFrom.value.file == null || taskFrom.value.file == '') {
                delete taskFrom.value.file
            }
            updateTask()
        } else {
            console.log('error submit!', fields)
            ElMessage.error('请填写必填项')
        }
    })
}

// 更新任务
const updateTask = () => {
    // 如果需要，在这里可以对文件数据进行额外处理
    const updateUserWorkParam = { ...taskFrom.value, endTime: ee.value, updateTime: Date.now().toString() }
    console.log(updateUserWorkParam);

    userUpdateTask(updateUserWorkParam).then((res) => {
        console.log(res);
        if (res.data.code == 200) {
            ElMessage.success('提交成功')
            router.go(-1)
        } else {
            ElMessage.error('提交失败')
        }
    })
}

// 关闭表单
const closeForm = () => {
    router.go(-1)
}

// 添加删除文件方法
const removeFile = () => {
    taskFrom.value.file = null;
    taskFrom.value.attachmentId = '';
    ElMessage.success('文件已移除');
}

onMounted(() => {
    // getTask()

})


</script>



<style lang="less">
.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 100%;
    /* 确保内容垂直居中 */
}

.div-icon {
    width: 10px;
    height: 20px;
    background-color: #335ca89a;
    margin-right: 5px;
}


.left-content {
    display: flex;
    align-items: center;
}

.buttons-right {
    display: flex;
    gap: 10px;
}


.form-container {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中（如果需要的话，但这里可能不需要，因为el-main通常会有自己的滚动条或填充） */
    height: 100%;
    /* 这通常不会起作用，因为el-main的高度由其内容决定 */
    width: 100%;
    /* 或者一个具体的值，比如80% */
}

.form-frame {
    width: 30%;
}

@media (max-width: 1200px) {
    .form-frame {
        width: 40%;
    }
}

@media (max-width: 1000px) {
    .form-frame {
        width: 60%;
    }
}

@media (max-width: 800px) {
    .form-frame {
        width: 80%;
    }
}



@media (max-width: 600px) {
    .form-frame {
        width: 100%;
    }

    .buttons-right {
        gap: 0;
    }

    .div-icon {
        margin-right: 0px;
    }
}

/* 添加文件显示样式 */
.file-display {
    margin-top: 10px;
    padding: 8px 12px;
    background-color: #f4f4f5;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.file-name {
    color: #606266;
    font-size: 14px;
}

.delete-icon {
    margin-left: auto;
    color: #909399;
    cursor: pointer;

    &:hover {
        color: #f56c6c;
    }
}
</style>